#!/usr/bin/env python
# -*- coding: utf-8 -*

import locale,sys,traceback
import _curses, curses,curses.ascii,types
import lib.keys as keys
import lib.pypad as pypad

locale.setlocale(locale.LC_ALL, '')
code = locale.getpreferredencoding()

lines = [line for line in open("messages.py","r")]

try:
    page=(0,0)
    cursor=(0,0)
    stdscr = curses.initscr()

    y,x = stdscr.getmaxyx()
    pp = pypad.PyPad(stdscr,lines,dx={"x":10,"y":0}, size={"width":x,"height":y-1})
    pp.page["top"]=5
    curses.noecho();curses.cbreak();stdscr.keypad(0)
    
    char = ""
    curses.halfdelay(2)
    key=0
    
    
    curses.curs_set(2)
    curses.start_color()
    curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
    
    y,x = stdscr.getmaxyx()
    pp.size = {"width":x-10,"height":y-1}
    click = 0
    pp.build()

    keyss = ["-1","-1","-1","-1","-1","-1"]

    while char!='esc':
	
	#stdscr.move(cursor[0],cursor[1])
	y,x = stdscr.getmaxyx()
	pp.size = {"width":x-10,"height":y-1}
	
	cursor = pp.set_cursor(cursor[0],cursor[1])

	key=stdscr.getch()
	
	keyss = keyss[1:]+[str(key)]
	
	if (key<256):
	    char = keys.parseKey(key)
	    if(char!=None):
		if (len(char)==1):
	    	    d = pp.insert(char,cursor[0],cursor[1])
	    	    if(key not in [208,209]):
	    		cursor = (cursor[0]+1,cursor[1])
	    	    click+=1
		else:
		    if (char=="up"):     cursor = (cursor[0],cursor[1]-1)
		    elif (char=="down"): cursor = (cursor[0],cursor[1]+1)
		    elif (char=="left"): cursor = (cursor[0]-1,cursor[1])
		    elif (char=="right"):cursor = (cursor[0]+1,cursor[1])
		    elif (char=="page up"): pp.pageup()
		    elif (char=="page down"): pp.pagedown()
		    elif (char=="backspace"): pp.bs(cursor[0],cursor[1]); cursor = (cursor[0] - 1 ,cursor[1])
		    elif (char=="delete"): pp.delete(cursor[0],cursor[1]);
	else:
	    stdscr.clear()

	menu_line = " CURSOR:[%d:%d]" % cursor
	menu_line += " XY:[%d:%d]" % (cursor[0]+pp.page["left"],cursor[1]+pp.page["top"])
	menu_line += " Click:%d" % click
	menu_line += " [%s]" % str(" ".join(keyss))
	
	menu_line += " [%s][%s]" % (str(chr(208)),str(chr(209)) )
	
	
	menu_line += "".join([" " for i in range(x-len(menu_line)-2)])
	stdscr.addstr(y-1,1,menu_line,curses.color_pair(1))
	stdscr.refresh()
	
except Exception,e:
    pass
finally:
    curses.nocbreak(); stdscr.keypad(0); curses.echo()
    curses.endwin()

traceback.print_exc(file=sys.stdout)
print "KEY:"+str(key)